import { IPQElement } from "@/interface";

function PriorityQueue() {

  this.items = [];

  function Node(element: any, priority: number) {
    this.element = element;
    this.priority = priority;
  }

  PriorityQueue.prototype.enqueue = function (element: any, priority: number): void {
    // @ts-ignore
    const queueElement = new Node(element, priority);
    if (this.isEmpty()) {
      this.items.push(queueElement);
    } else {
      let added = false;
      for (let i = 0; i < this.items.length; i++) {
        if (queueElement.priority < this.items[i].priority) {
          this.items.splice(i, 0, queueElement);
          added = true;
          break;
        }
      }
      // 如果新插入的元素比队列中任何一个元素的优先级都低的话, 就把他插入到最后
      if (!added) {
        this.items.push(queueElement)
      }
    }
  }
  PriorityQueue.prototype.dequeue = function (): IPQElement {
    /**
     * @description 移除队列的第一个元素
     * @return {IPQElement} 返回被移除的元素
     **/
    return this.items.shift();
  }
  PriorityQueue.prototype.front = function (): IPQElement {
    /**
     * @decription 查看队列的第一个元素
     * @return {IPQElement} 返回队列的第一个元素
     **/
    return this.items[0];
  }
  PriorityQueue.prototype.isEmpty = function (): boolean {
    return this.items.length === 0;
  }
  PriorityQueue.prototype.size = function (): number {
    return this.items.length;
  }
  PriorityQueue.prototype.toString = function (): string {
    return this.items.toString()
  }
  PriorityQueue.prototype.clear = function (): void {
    this.items = [];
  }
}


export {
  PriorityQueue
}